#include <gtest/gtest.h>
#include "camera_video_enc.h"
#include "base_log.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <fstream>  // 添加这行来包含 fstream 头文件

// 使用命名空间以简化代码
using namespace El;
using namespace El::Hal;

// 添加新的测试用例
TEST(CameraTest, SnapshotTest) {
    ICameraVideoEnc &camera = ICameraVideoEnc::GetInstance(0, MEDIA_VIDEO_ENC_STREAM_SNAPSHOT);
    std::atomic<bool> snapshotReceived(false);
    std::condition_variable cv;
    std::mutex mtx;

    // 注册回调函数
    auto callback = [&](const VideoEncPacket& packet) {
        if (packet.frameType == MEDIA_FRAME_JPEG) {
            LOG_INFO("Received snapshot: size={}, width={}, height={}", 
                     packet.len, packet.width, packet.height);
            
            // 保存快照到文件
            std::ofstream outfile("snapshot.jpg", std::ios::binary);
            outfile.write(reinterpret_cast<const char*>(packet.buf), packet.len);
            outfile.close();

            snapshotReceived = true;
            cv.notify_one();
        }
    };

    // 启动抓图
    int handle = camera.Start(callback);
    ASSERT_GE(handle, 0) << "Failed to start snapshot";

    // 触发抓图
    ASSERT_EQ(camera.Snapshot(), 0) << "Failed to trigger snapshot";

    // 等待抓图完成
    {
        std::unique_lock<std::mutex> lock(mtx);
        ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&]{ return snapshotReceived.load(); }))
            << "Timeout waiting for snapshot";
    }

    // 停止抓图
    camera.Stop(handle);

    // 验证文件是否存在
    std::ifstream file("snapshot.jpg");
    ASSERT_TRUE(file.good()) << "Snapshot file not created";
    file.close();

    LOG_INFO("Snapshot test completed successfully");
}
